package net.zjitc.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import net.zjitc.common.lang.Level;
import net.zjitc.common.ResponseResult;
import net.zjitc.common.lang.LevelStr;
import net.zjitc.entity.PermissionApi;
import net.zjitc.entity.Permission;
import net.zjitc.entity.Role;
import net.zjitc.exception.PermissionException;
import net.zjitc.mapper.PermissionApiMapper;
import net.zjitc.mapper.PermissionMapper;
import net.zjitc.mapper.RoleMapper;
import net.zjitc.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 毛钰深
 * @create 2022/1/27
 */
@Service
@Transactional
public class IPermissionService implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionApiMapper permissionApiMapper;

    private List<Permission> permissionList;

    private List<PermissionApi> permissionApis;

    /**
     * 所有权限列表
     * @param type
     * @return
     * @throws PermissionException
     */
    @Override
    public ResponseResult selectPermission(String type) throws PermissionException {
        if(!type.equals("list") && !type.equals("tree")) {
            throw new PermissionException("参数错误");
        }
        ResponseResult res = new ResponseResult();
        this.permissionList = permissionMapper.selectList(null);
        this.permissionApis = permissionApiMapper.selectList(null);
        setThePath(permissionList,permissionApis);

        if (type.equals("list")) {
            res.setSuccess("获取权限列表成功",permissionList);
        } else {
            List<Permission> levelOne = getRightList(LevelStr.LEVEL_ONE_STR.level);
            List<Permission> levelTwo = getRightList(LevelStr.LEVEL_TWO_STR.level);
            List<Permission> levelThree = getRightList(LevelStr.LEVEL_THREE_STR.level);
            merge(levelOne, levelTwo);
            merge(levelTwo, levelThree);

            res.setSuccess("获取权限列表成功",levelOne);
        }
        return res;
    }

    private void setThePath(List<Permission> permissionList, List<PermissionApi> permissionApis) {
        permissionList.forEach(p -> {
            for (PermissionApi permissionApi : permissionApis) {
                if (permissionApi.getPs_id().equals(p.getId())){
                    p.setPath(permissionApi.getPs_api_path());
                    break;
                }
            }
        });
    }

    /**
     * 左侧菜单权限
     * 可以添加缓存,提高效率
     * @return
     */
    @Override
    public ResponseResult selectLeftPermission(int rid) {
        ResponseResult<List> res = new ResponseResult<>();

        //根据拥有的角色来获取菜单相关列表
        if (rid!=0){
            Role role = roleMapper.selectById(rid);
            if (role!=null){
                String[] split = role.getPsIds().split(",");
                permissionList = permissionMapper.selectList(Wrappers.lambdaQuery(Permission.class).in(Permission::getId,split));
                List<Integer> rights = permissionList.stream().map(right -> right.getId()).collect(Collectors.toList());
                permissionApis=permissionApiMapper.selectList(Wrappers.lambdaQuery(PermissionApi.class).in(PermissionApi::getPs_id,rights));
            }else{
                res.setNotFound("该用户的角色不存在或者已失效(删除)");
                return res;
            }
        }else{
            permissionList = permissionMapper.selectList(null);
            permissionApis=permissionApiMapper.selectList(null);
        }

        List<Permission> levelOne = getLeftPermissionList(LevelStr.LEVEL_ONE_STR.level);
        //设置每个二级的right对应的api_path
        List<Permission> levelTwo = getLeftPermissionList(LevelStr.LEVEL_TWO_STR.level);
        levelTwo.forEach(l->{
            permissionApis.forEach(p->{
                if (p.getPs_id().equals(l.getId())){
                    l.setPath(p.getPs_api_path());
                }
            });
        });
        mergeLeft(levelOne,levelTwo);

        res.setSuccess("获取菜单列表成功",levelOne);

        return res;
    }

    private List<Permission> getRightList(String level) {
        List<Permission> list = new ArrayList<>();
        for (Permission right : this.permissionList) {
            if (level.equals(right.getLevel())) {
                right.setLevel(null);
                list.add(right);
            }
        }
        return list;
    }

    private void merge(List<Permission> parents, List<Permission> childrens) {
        for (Permission parent : parents) {
            List<Permission> child = new ArrayList<>();
            for (Permission children : childrens) {
                if (children.getPid().equals(parent.getId())) {
                    child.add(children);
                }
            }
            parent.setChildren(child);
        }
    }

    private List<Permission> getLeftPermissionList(String type) {
        List<Permission> list = new ArrayList<>();
        for (Permission right : this.permissionList) {
            if (type.equals(right.getLevel())) {
                right.setLevel(null);
                right.setChildren(new ArrayList<>());
                list.add(right);
            }
        }
        return list;
    }

    private void mergeLeft(List<Permission> parents, List<Permission> childrens) {
        for (Permission parent : parents) {
            List<Permission> child = new ArrayList<>();
            for (Permission children : childrens) {
                if (parent.getId().equals(children.getPid())) {
                    children.setPid(null);
                    child.add(children);
                }
            }
            parent.setPid(null);
            parent.setChildren(child);
        }
    }

}
